const chromeMng = require('../mng/chromeMng')
const logger = require('log4js').getLogger()
const config = require('../util/config')
const Wechat = require('../util/Wechat')
const ChromeServerIterator = require('../mng/chromeServerMng').Iterator
const taobaoLoginResolveMng = require('../mng/taobaoLoginResolveMng')

exports.start = () => {
    if (config.domain == '') {
        chromeMng.getTaobaoBill().then(result => {
            exports.getTaobaoBillResolve(result)
        }, result => {
            logger.error('[' + __filename + ':' + __line + ']', result)
        })
    } else if (config.domain == 'zoro.site') {
        var chromeServerIterator = new ChromeServerIterator()
        var noChromeServer = true
        while (1) {
            let chromeServer = chromeServerIterator.next()
            if (!chromeServer)
                break
            let firstChromServer = noChromeServer
            noChromeServer = false

            getTaobaoBillFromChromeServer(chromeServer).then(result => {
                if (taobaoLoginResolveMng.hasResolve) {
                    taobaoLoginResolveMng.hasResolve = false
                    taobaoLoginResolveMng.resolve()
                }
            }, result => {
                // if (firstChromServer) {
                // require('../mng/pushMng').push(JSON.stringify(result))
                // }
            })
        }
        if (noChromeServer) {
            // require('../mng/pushMng').push('no chrome server')
            return
        }
    }
}

exports.getTaobaoBillResolve = result => {
    if (!result) {
        return
    }
    const mongoMng = require('../mng/mongoMng')
    if (!mongoMng.db) {
        return
    }
    while (result.length > 0) {
        let item = result.splice(0, 1)[0]
        if (!item.tradeParentId) {
            continue
        }
        let num = 1
        for (let i = 0; i < result.length;) {
            if (result[i].tradeParentId == item.tradeParentId &&
                result[i].itemId == item.itemId &&
                result[i].itemNum == item.itemNum &&
                result[i].alipayTotalPrice == item.alipayTotalPrice) {
                result.splice(i, 1)
                ++num
            } else {
                ++i
            }
        }
        // if (num > 1) {
        //     logger.warn('[' + __filename + ':' + __line + ']', num, item)
        //     continue
        // }
        let filter = {
            tradeParentId: item.tradeParentId,
            itemId: item.itemId,
            itemNum: item.itemNum,
            alipayTotalPrice: item.alipayTotalPrice
        }
        mongoMng.db.collection('bill').countDocuments(filter, (err, result) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                return
            }
            if (result > 0 && num != result) {
                logger.warn('[' + __filename + ':' + __line + ']', JSON.stringify(filter), num, result)
                return
            }
            mongoMng.db.collection('bill').updateMany(filter, {
                $set: item
            }, {
                    multi: true
                }, (err, _result) => {
                    if (err) {
                        logger.error('[' + __filename + ':' + __line + ']', err)
                        return
                    }
                    if (result < num) {
                        // 少了就插入
                        logger.debug('[' + __filename + ':' + __line + ']', JSON.stringify(filter), 'insert', num - result)
                        let docs = []
                        for (let i = 0; i + result < num; ++i) {
                            docs.push(JSON.parse(JSON.stringify(item)))
                        }
                        mongoMng.db.collection('bill').insert(docs, (err, result) => {
                            if (err) {
                                logger.error('[' + __filename + ':' + __line + ']', err)
                                return
                            }
                            require('./handleBillTask').findCustomerForBill(item).then(result => {
                                var str = '有新淘宝订单[' + item.tradeParentId + ',' + item.itemId + ',' + item.itemNum + ',' + item.alipayTotalPrice + ',' + result + ',' + item.fromUsername + ']'
                                logger.debug('[' + __filename + ':' + __line + ']', str)
                                require('../mng/pushMng').push(str)
                            }, result => {
                                var str = '有新淘宝订单[' + item.tradeParentId + ',' + item.itemId + ',' + item.itemNum + ',' + item.alipayTotalPrice + ',' + item.fromUsername + ']'
                                logger.debug('[' + __filename + ':' + __line + ']', str)
                                require('../mng/pushMng').push(str)
                            })
                        })
                    } else if (result > num) {
                        // 多了就删除
                        logger.debug('[' + __filename + ':' + __line + ']', JSON.stringify(filter), 'delete', result - num)
                        for (let i = 0; i + num < result; ++i) {
                            mongoMng.db.collection('bill').deleteOne(filter, (err, result) => {
                                if (err) {
                                    logger.error('[' + __filename + ':' + __line + ']', err)
                                    return
                                }
                            })
                        }
                    }
                })
        })
    }
}

function getTaobaoBillFromChromeServer(chromeServer) {
    return new Promise((resolve, reject) => {
        var url = chromeServer + 'getTaobaoBill.do'
        require('../util/getHtml')({
            url,
            data: JSON.stringify({})
        }).then(result => {
            var obj = JSON.parse(result)
            if (obj.result == 1) {
                exports.getTaobaoBillResolve(obj.taobaoBill)
                resolve()
            } else {
                logger.error('[' + __filename + ':' + __line + ']', url, result)
                reject(obj)
            }
        }, result => {
            logger.error('[' + __filename + ':' + __line + ']', url, JSON.stringify(result))
            reject(result)
        })
    })
}